/*
 * MIT License
 *
 * Copyright (c) 2021 cao.yong<cymsn81@126.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package org.cy.websocket.stomp.messaging;

import org.cy.websocket.stomp.StompCommand;
import org.cy.websocket.stomp.StompHeaders;

import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created in 2021-05-09 21:13
 *
 * @author cao.yong
 */
public class StompEncoder {

    private static final Byte LINE_FEED_BYTE = '\n';

    private static final Byte COLON_BYTE = ':';
    private static final int HEADER_KEY_CACHE_LIMIT = 32;


    private final Map<String, byte[]> headerKeyAccessCache = new ConcurrentHashMap<>(HEADER_KEY_CACHE_LIMIT);

    private final Map<String, byte[]> headerKeyUpdateCache =
            new LinkedHashMap<String, byte[]>(HEADER_KEY_CACHE_LIMIT, 0.75f, true) {
                @Override
                protected boolean removeEldestEntry(Map.Entry<String, byte[]> eldest) {
                    if (size() > HEADER_KEY_CACHE_LIMIT) {
                        headerKeyAccessCache.remove(eldest.getKey());
                        return true;
                    }
                    else {
                        return false;
                    }
                }
            };
    public byte[] encode(Message<byte[]> message) {
        return encode(message.getCommand(), message.getHeaders(), message.getPayload());
    }

    public byte[] encode(StompCommand command, StompHeaders headers, byte[] payload) {
        ContentResult contentResult = new DefaultContentResult();
        if (StompCommand.HEARTBEAT == command) {
            contentResult.add(payload);
        } else {
            contentResult.add(command.toString().getBytes(StandardCharsets.UTF_8));
            contentResult.add(LINE_FEED_BYTE);
            writeHeaders(command, headers, payload, contentResult);
            contentResult.add(LINE_FEED_BYTE);
            contentResult.add(payload);
            contentResult.add((byte) 0);
        }
        return contentResult.toByteArray();
    }

    private void writeHeaders(StompCommand command, StompHeaders headers, byte[] payload, ContentResult result) {
        boolean shouldEscape = (command != StompCommand.CONNECT && command != StompCommand.CONNECTED);
        for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
            if (command.isAllowBody() && "content-length".equals(entry.getKey())) {
                continue;
            }
            List<String> values = entry.getValue();
            byte[] encodedKey = encodeHeaderKey(entry.getKey(), shouldEscape);
            for (String value : values) {
                result.add(encodedKey);
                result.add(COLON_BYTE);
                result.add(encodeHeaderValue(value, shouldEscape));
                result.add(LINE_FEED_BYTE);
            }
        }
        if (command.isAllowBody()) {
            int contentLength = payload.length;
            result.add("content-length:".getBytes(StandardCharsets.UTF_8));
            result.add(Integer.toString(contentLength).getBytes(StandardCharsets.UTF_8));
            result.add(LINE_FEED_BYTE);
        }
    }

    private byte[] encodeHeaderKey(String input, boolean escape) {
        String inputToUse = (escape ? escape(input) : input);
        if (this.headerKeyAccessCache.containsKey(inputToUse)) {
            return this.headerKeyAccessCache.get(inputToUse);
        }
        synchronized (this.headerKeyUpdateCache) {
            byte[] bytes = this.headerKeyUpdateCache.get(inputToUse);
            if (bytes == null) {
                bytes = inputToUse.getBytes(StandardCharsets.UTF_8);
                this.headerKeyAccessCache.put(inputToUse, bytes);
                this.headerKeyUpdateCache.put(inputToUse, bytes);
            }
            return bytes;
        }
    }

    private byte[] encodeHeaderValue(String input, boolean escape) {
        String inputToUse = (escape ? escape(input) : input);
        return inputToUse.getBytes(StandardCharsets.UTF_8);
    }

    private String escape(String inString) {
        StringBuilder sb = null;
        for (int i = 0; i < inString.length(); i++) {
            char c = inString.charAt(i);
            if (c == '\\') {
                sb = getStringBuilder(sb, inString, i);
                sb.append("\\\\");
            }
            else if (c == ':') {
                sb = getStringBuilder(sb, inString, i);
                sb.append("\\c");
            }
            else if (c == '\n') {
                sb = getStringBuilder(sb, inString, i);
                sb.append("\\n");
            }
            else if (c == '\r') {
                sb = getStringBuilder(sb, inString, i);
                sb.append("\\r");
            }
            else if (sb != null){
                sb.append(c);
            }
        }
        return (sb != null ? sb.toString() : inString);
    }

    private StringBuilder getStringBuilder(StringBuilder sb, String inString, int i) {
        if (sb == null) {
            sb = new StringBuilder(inString.length());
            sb.append(inString, 0, i);
        }
        return sb;
    }
}
